package com.ruoyi.common.utils;

import com.ruoyi.common.utils.cover.ICoverLife;
import com.ruoyi.common.vo.PageVO;
import com.google.common.collect.Lists;
import java.util.List;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

public class BeanConvertUtils {
    private static final Logger log = LoggerFactory.getLogger(BeanConvertUtils.class);

    public BeanConvertUtils() {
    }

    public static <T> PageVO<T> convertPage(PageVO<? extends Object> pageEntity, Class<T> targetClass) {
        return convertPage(pageEntity, targetClass, (ICoverLife)null);
    }

    public static <T> PageVO<T> convertPage(PageVO<? extends Object> pageEntity, Class<T> targetClass, ICoverLife<?, T> coverLife) {
        PageVO<T> pageVO = new PageVO();
        pageVO.setTotalPage(pageEntity.getTotalPage());
        pageVO.setTotalCount(pageEntity.getTotalCount());
        pageVO.setCurrent(pageEntity.getCurrent());
        pageVO.setSize(pageEntity.getSize());
        List<T> list = convert(pageEntity.getList(), targetClass, coverLife);
        pageVO.setList(list);
        return pageVO;
    }

    public static <T> List<T> convert(List<? extends Object> sourceList, Class<T> targetClass) {
        return convert(sourceList, targetClass, (ICoverLife)null);
    }

    public static <T> List<T> convert(List<? extends Object> sourceList, Class<T> targetClass, ICoverLife<?, T> coverLife) {
        if (sourceList != null && sourceList.size() != 0) {
            List<T> targetList = Lists.newArrayListWithCapacity(sourceList.size());

            for(Object source : sourceList) {
                T target = null;

                try {
                    target = (T)targetClass.newInstance();
                    BeanUtils.copyProperties(source, target);
                    if (coverLife != null) {
                        coverLife.after(source, target);
                    }

                    targetList.add(target);
                } catch (Exception e) {
                    log.error(ExceptionUtils.getStackTrace(e));
                }
            }

            return targetList;
        } else {
            return Lists.newArrayList();
        }
    }

    public static <T> T convert(Object source, Class<T> targetClass) {
        try {
            if (source == null) {
                return (T)targetClass.newInstance();
            } else {
                T target = (T)targetClass.newInstance();
                BeanUtils.copyProperties(source, target);
                return target;
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            return null;
        }
    }

    public static void convert(Object source, Object target) {
        BeanUtils.copyProperties(source, target);
    }
}


